<template>
  <div class="app-content">
    <div class="form_wrap">
        <uni-list>
          <uni-list-item title="部门名称" :custom="true" :show-arrow="false">
			<div class="inputTip_box">
            	<input type="text" placeholder="请输入部门名称" v-model="form.name" @blur="validateDepartment">
				<span class="inputTip">{{departmentInputTips}}</span>
			</div>
          </uni-list-item>
          <uni-list-item title="上级部门" :show-arrow="false" :text="upperDepartment"></uni-list-item>
        </uni-list>
      <div class="submit_btn"
           @click="save">保存</div>
    </div>
  </div>
</template>

<script>
// import { setTimeout } from 'timers';
import { addDepartment, departmentDetail, editDepartment } from '@/api/staffManage'
import uniList from '@/components/uni-list/uni-list'
import uniListItem from '@/components/uni-list-item/uni-list-item'
const departmentReg = /^[\u4E00-\u9FA5A-Za-z0-9]{0,19}[\s]{0,1}$/
export default {
	name: 'AddDepartment',
	components: {
		uniList,
		uniListItem
	},
	data() {
		return {
			form: {
				name: ''
			},
			upperDepartment: '',
			departmentInputTips: '',
			option: {}
		}
	},
	onLoad(option) {
		this.option = option
		this.getDepartmentInfo()
	},
	methods: {
		getDepartmentInfo() {
			departmentDetail({ department_id: this.option.department_id }).then((res) => {
				this.upperDepartment = res.data.info.name || ''
			})
			if (this.option.id) {
				departmentDetail({ department_id: this.option.id }).then((res) => {
					this.form.name = res.data.info.name || ''
				})
			}
		},
		validateDepartment() {
			if (departmentReg.test(this.form.name) || !this.form.name) {
				this.departmentInputTips = ''
			} else if (this.form.name) {
				this.departmentInputTips = '格式错误'
			}
		},
		postForm() {
			if (this.option.id) {
				return editDepartment({ ...this.form, department_id: this.option.id })
			} else {
				return addDepartment({ ...this.form, department_id: this.option.department_id })
			}
		},
		save() {
			if (!this.form.name) {
				uni.showToast({
					title: '请填写部门名称',
					icon: 'none'
				})
			} else if (this.departmentInputTips) {
				return
			} else {
				this.postForm().then((res) => {
					uni.showToast({
						title: this.option.id ? '修改成功' : '添加成功',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})
					}, 500)
				})
			}
		}
	}
}
</script>

<style scoped>
    .form_wrap {
        margin-top: 20px;
    }
    .label {
        font-size: 28px;
        color: rgba(102, 102, 102, 1);
    }
    .submit_btn {
        margin: 60px auto 0;
        width: calc(100% - 60px);
        height: 90px;
        line-height: 90px;
        background: rgba(255, 209, 26, 1);
        text-align: center;
        border-radius:10px;
        font-size:24px;
        color: rgba(58, 27, 4, 1);
    }
</style>
